import { defineStore } from 'pinia'
import type { IDialog, IHandleApi, IStatsChart } from 'vue3-common/types'
import { ElMessage } from 'element-plus'
import { IJournal, IJournalQuery } from '@/types/journal.ts'
import { addJournalApi, deleteJournalApi, queryJournalApi, updateJournalApi } from '@/apis/journal.ts'
import { ImagePathEnum } from '@/types'

export const useJournalStore = defineStore('journal', {
  state: () => ({
    journalList: [] as IJournal[],
    queryInfo: {
      startDate: '',
      endDate: ''
    } as IJournalQuery,
    journalApiType: 'ADD' as IHandleApi,
    categoryStats: {} as IStatsChart[],
    currentJournal: {
      id: 0,
      date: '',
      location: '',
      category: '',
      weather: '',
      mood: '',
      content: '',
      imageUrl: '',
      videoUrl: ''
    } as IJournal,
    journalImagePath: ImagePathEnum.JOURNAL,
    journalVideoPath: ImagePathEnum.JOURNAL,
    journalDialog: {
      visible: false,
      title: '',
      data: {}
    } as IDialog<IJournal>,
    isRefresh: false
  }),
  actions: {
    async queryJournalList() {
      this.journalList = await queryJournalApi(this.queryInfo)
    },
    async handleJournalApi(journal: IJournal) {
      switch (this.journalApiType) {
        case 'ADD':
          await addJournalApi(journal)
          ElMessage.success('新增日记成功')
          break
        case 'UPDATE':
          await updateJournalApi(journal.id as number, journal)
          ElMessage.success('更新日记成功')
          break
        case 'DELETE':
          await deleteJournalApi(journal.id as number)
          ElMessage.success('删除日记成功')
          break
        default:
          break
      }
      this.journalDialog.visible = false
      await this.refreshInfo()
    },
    async refreshInfo() {
      await this.queryJournalList()
      this.isRefresh = !this.isRefresh
    },
    getEmptyJournal(): IJournal {
      return {
        id: 0,
        category: '',
        content: '',
        date: '',
        imageUrl: '',
        location: '',
        mood: '',
        videoUrl: '',
        weather: ''
      }
    }
  }
})
